package com.msk.web.controller.wlhy;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.msk.common.core.controller.BaseController;
import com.msk.common.core.domain.R;
import com.msk.common.core.domain.model.LoginUser;
import com.msk.framework.web.utils.TokenUtils;
import com.msk.sys.domain.Dict;
import com.msk.sys.service.DictService;
import com.msk.sys.utils.DictMskUtils;
import com.msk.sys.utils.createNumber;
import com.msk.wlhy.domain.*;
import com.msk.wlhy.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author llh
 * @date 2023/5/6
 * @description 司机首页信息接口
 */
@Api(tags = "司机首页信息接口")
@RestController
@RequestMapping("/api/driverHomePage")
public class DriverHomePageController extends BaseController {

    @Autowired
    private HtCarFilesService htCarFilesService;

    @Autowired
    private HtDriverFileService htDriverFileService;

    @Autowired
    private HtLogisticsOrderDetailService htLogisticsOrderDetailService;

    @Autowired
    private HtTransportListService htTransportListService;

    @Autowired
    private HtTransportDetailService htTransportDetailService;

    @Autowired
    private DictService dictService;

    /**
     * @author llh
     * @date 2023/5/6
     * @return com.msk.common.core.domain.R<?>
     * @description 当前司机对应部门所有货源信息接口
     */
    @ApiOperation("当前司机对应部门所有货源信息接口")
    @PostMapping(value = "/orderDetailList")
    public R<?> orderDetailList(@RequestBody Map<String, Object> paramMap) {
        List<Map<String, Object>> list = new ArrayList<>();
        HtLogisticsOrderDetail htLogisticsOrderDetail = new HtLogisticsOrderDetail();
        htLogisticsOrderDetail.setStatus("2");
        htLogisticsOrderDetail.setAttstr03("1");
        //移动端只能接直接发布方式的货源订单
        htLogisticsOrderDetail.setPublishWay("1");
        HtDriverFile driverFile = TokenUtils.getDriverLogin();
        HashMap<String, Object> map = new HashMap<>();
        if (driverFile != null) {
            HtCarFiles htCarFiles = null;
            if ("1".equals(driverFile.getIsPassCheck())) {
                htCarFiles = htCarFilesService.findCarFilesByDriverId(driverFile.getId());
                if (paramMap.size() != 0 || paramMap != null) {
                    htLogisticsOrderDetail.getParams().put("pageNum", paramMap.get("pageNum"));
                    htLogisticsOrderDetail.getParams().put("pageSize", paramMap.get("pageSize"));
                }
                htLogisticsOrderDetail.getParams().put("orderByStr", "a.create_date desc");
                startPageJson(htLogisticsOrderDetail.getParams(), "");
                list = htLogisticsOrderDetailService.findDriverGoods(htLogisticsOrderDetail);
                //计算剩余重量总运费
                for (Map result : list) {
                    String priceWay = String.valueOf(result.get("priceWay"));
                    String distance = String.valueOf(result.get("distance"));
                    Double freight = (Double) result.get("freight");
                    Double goodsWeight = (Double) result.get("goodsWeight");
                    String carNum = String.valueOf(result.get("carNum"));
                    if (result.get("goodsWeight") != null && result.get("freight") != null) {
                        if ("1".equals(priceWay) && StringUtils.isNotBlank(distance)) {
                            //吨公里 单价*运距*重量
                            result.put("surplusPrice", (new BigDecimal(freight * Double.parseDouble(distance) * goodsWeight).setScale(2, RoundingMode.HALF_DOWN)).doubleValue());
                        } else if ("2".equals(priceWay) && StringUtils.isNotBlank(distance)) {
                            //整车 车数*单价
                            result.put("surplusPrice", (new BigDecimal(freight * Double.parseDouble(carNum)).setScale(2, RoundingMode.HALF_DOWN)).doubleValue());
                        } else {
                            //元/吨 单价*重量
                            result.put("surplusPrice", (new BigDecimal(freight * Double.parseDouble("1") * goodsWeight).setScale(2, RoundingMode.HALF_DOWN)).doubleValue());
                        }
                    } else {
                        result.put("surplusPrice", result.get("revicePrice"));
                    }
                }
                map.put("list", list);
            }
            map.put("carload", htCarFiles != null ? htCarFiles.getCarLoad() : "");
            map.put("count", new PageInfo<>(list).getTotal());
            map.put("isOverload", dictService.findByTypeAndLabel("is_overload", "overload_setting"));
        }
        return R.appOk(map);
    }

    /**
     * @author llh
     * @date 2023/5/23
     * @return com.msk.common.core.domain.R<?>
     * @description 查看货源详情
     */
    @ApiOperation("查看货源详情")
    @PostMapping("/showGoodsDetails")
    public R<?> showGoodsDetails(@RequestBody HtLogisticsOrderDetail htLogisticsOrderDetail) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        HtLogisticsOrderDetail result = null;
        if (loginUser != null) {
            result = htLogisticsOrderDetailService.selectDetailById(htLogisticsOrderDetail);
            String goodsType = result.getGoodsType();
            List<Dict> goodsTypeDictList = DictMskUtils.getDictListNew("goods_type");
            if (goodsType != null && com.msk.common.utils.StringUtils.isNotEmpty(goodsTypeDictList)) {
                String goodsTypeAlias = DictMskUtils.getDictLabelNew(goodsType, goodsTypeDictList, "");
                result.setGoodsTypeAlias(goodsTypeAlias);
            }
        }
        //设置当前司机车辆载重
        HtDriverFile driverFile = TokenUtils.getDriverLogin();
        HtCarFiles htCarFiles = htCarFilesService.findCarFilesByDriverId(driverFile.getId());
        result.setCarLoad(String.valueOf(htCarFiles.getCarLoad()));
        result.setIsOverload(dictService.findByTypeAndLabel("is_overload", "overload_setting"));
        return R.appOk(result);
    }

    /**
     * @author llh
     * @date 2023/5/11
     * @return com.msk.common.core.domain.R<?>
     * @description 小程序司机接单接口
     */
    @ApiOperation("小程序司机接单接口")
    @PostMapping(value = "/addTransportList")
    public R<?> addTransportList(@RequestBody Map<String, String> map) {
        Map<String, Object> result = Maps.newHashMap();
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        try {
            HtDriverFile driverFile = htDriverFileService.getDriverByUserId(loginUser.getLoginId());
            HtTransportList htTransportList = new HtTransportList();

            HtTransportDetail htTransportDetail = new HtTransportDetail();
            htTransportDetail.setAttstr03(driverFile.getId());
            htTransportDetail.setStatus("1");
            HtTransportDetail htTransportDetailQuery = new HtTransportDetail();
            htTransportDetailQuery.setDriverId(driverFile.getId());
            List<HtTransportDetail> list1 = htTransportDetailService.getTransportDetailByDriverId(htTransportDetailQuery);
            if (list1.size() > 0) {
                result.put("flag", false);
                result.put("message", "当前还有未完成的订单信息,请先完成或者删除");
                return R.appOk(result);
            }
            HtLogisticsOrderDetail htLogisticsOrderDetail = htLogisticsOrderDetailService.get(map.get("id"));
            String priceWay = htLogisticsOrderDetail.getPriceWay();
            BigDecimal allFreight = new BigDecimal("0");
            if ("1".equals(priceWay)) {
                //吨公里
                allFreight = new BigDecimal(htLogisticsOrderDetail.getFreight() * Double.parseDouble(map.get("goodsWeight")) * Double.parseDouble(htLogisticsOrderDetail.getDistance())).setScale(2, RoundingMode.HALF_DOWN);
            } else if ("2".equals(priceWay)) {
                //整车 车辆数默认1
                allFreight = new BigDecimal(htLogisticsOrderDetail.getFreight() * Double.parseDouble("1")).setScale(2, RoundingMode.HALF_DOWN);
            } else if ("3".equals(priceWay)) {
                //元吨
                allFreight = new BigDecimal(htLogisticsOrderDetail.getFreight() * Double.parseDouble(map.get("goodsWeight"))).setScale(2, RoundingMode.HALF_DOWN);
            } else {
                allFreight = new BigDecimal(htLogisticsOrderDetail.getFreight() * Double.parseDouble(map.get("goodsWeight")) * Double.parseDouble(htLogisticsOrderDetail.getDistance())).setScale(2, RoundingMode.HALF_DOWN);
            }
            HtCarFiles htCarFiles = new HtCarFiles();
            htCarFiles.setPhone(loginUser.getUsername());
            htCarFiles.setOffice(htLogisticsOrderDetail.getOffice());
            htCarFiles = htCarFilesService.getCarFilesByPhone(htCarFiles);
            //设置允许超载比例
            Double goodsWeight = Double.parseDouble(map.get("goodsWeight"));
            String isOverload = dictService.findByTypeAndLabel("is_overload", "overload_setting");
            if("1".equals(isOverload)){
                String overloadProportion = dictService.findByTypeAndLabel("overload_proportion", "overload_setting");
                BigDecimal allowableWeight = new BigDecimal(htCarFiles.getCarLoad() * (1 + (Double.parseDouble(overloadProportion))/100)).setScale(3, RoundingMode.HALF_DOWN);
                if(goodsWeight > allowableWeight.doubleValue()){
                    result.put("flag", false);
                    result.put("message", "接单重量不能超过车辆核载重量");
                    return R.appOk(result);
                }
            }else{
                if(goodsWeight > htCarFiles.getCarLoad()){
                    result.put("flag", false);
                    result.put("message", "接单重量不能超过车辆核载重量");
                    return R.appOk(result);
                }
            }

            htLogisticsOrderDetail = htTransportListService.updateOrderDetailInfo(htTransportList, htLogisticsOrderDetail, map.get("goodsWeight"), loginUser);

            String htCode = DictMskUtils.getDictLabel("PCD", "ht_code", "");
            String dispatchCarNumber = createNumber.getNewOrderNo(htCode);//生成新派车单号
            String barCode = createNumber.getOrderNo("");// 生成条码
            htTransportList.setDispatchCarNumber(dispatchCarNumber);
            htTransportList.setBarCode(barCode);
            htTransportList.setCarId(htCarFiles.getId());
            htTransportList.setDispatchTime(new Date());// 派车时间
            htTransportList.setIsEnter("1");
            htTransportList.setIsOrders("1");
            htTransportList.setCompany(htLogisticsOrderDetail.getCompany());
            htTransportList.setOffice(htLogisticsOrderDetail.getOffice());
            // 设置通用属性
            htTransportDetail.setCreateDate(new Date());
            htTransportDetail.setOrderNo(dispatchCarNumber);
            htTransportDetail.setGoodsWeight(htLogisticsOrderDetail.getGoodsWeight());
            htTransportDetail.setStartArea(htLogisticsOrderDetail.getLoadingArea());
            htTransportDetail.setStartAreaName(htLogisticsOrderDetail.getLoadingAreaName());
            htTransportDetail.setStartPlace(htLogisticsOrderDetail.getLoadingPlace());
            htTransportDetail.setEndArea(htLogisticsOrderDetail.getUnloadingArea());
            htTransportDetail.setEndAreaName(htLogisticsOrderDetail.getUnloadingAreaName());
            htTransportDetail.setEndPlace(htLogisticsOrderDetail.getUnloadingPlace());
            htTransportDetail.setOrderDetailId(htLogisticsOrderDetail.getId());
            htTransportDetail.setGoodsName(htLogisticsOrderDetail.getGoodsName());
            htTransportDetail.setAttstr05(htLogisticsOrderDetail.getMeasureUnit());
            htTransportDetail.setFreight(htLogisticsOrderDetail.getFreight());
            htTransportDetail.setAllFreight(allFreight.doubleValue());
            htTransportDetail.setPrice(htLogisticsOrderDetail.getPrice());
            HtDriverFile driverLogin = TokenUtils.getDriverLogin();
            htTransportDetail.setCompany(driverLogin.getCompany());
            htTransportDetail.setOffice(driverLogin.getOffice());
            htTransportDetail.setAttstr03(driverFile.getId());
            //设置车辆起始经纬度坐标
            htTransportDetail.setStartCoordinate(htLogisticsOrderDetail.getStartCoordinate());
            htTransportDetail.setEndCoordinate(htLogisticsOrderDetail.getEndCoordinate());

            List<HtTransportDetail> list = new ArrayList<HtTransportDetail>();
            list.add(htTransportDetail);

            htTransportList.setHtTransportDetailList(list);
            htTransportList.setAttstr01(driverFile.getId());
            htTransportList.setAttstr02("1");
            htTransportList.setStatus("1");
            htTransportListService.saveWayBillData(htTransportList);

            driverLogin.setDriverStatus("1");//待运
            htDriverFileService.updatedriverStatus(driverLogin);

            result.put("flag", true);
            result.put("message", "接单成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("flag", false);
            result.put("message", e.toString());
        }
        return R.appOk(result);
    }
}
